package com.cms.menu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import com.cms.bean.MenuBean;
import com.cms.facade.SessionFacade;

public class MenuHelper {

	private static final String GET_ALL_MENU = "select * from admin_menus order by id ";
	
	
	@SuppressWarnings("finally")
	public static MenuBean getRootMenuBean(Connection conn) {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		MenuBean root = null;
		try {
			root = new MenuBean();
			root.setId(0);
			root.setMenuName("ROOTMENU");

			stmt = conn.prepareStatement(GET_ALL_MENU);
			rs = stmt.executeQuery();
			while (rs.next()) {
				MenuBean node = new MenuBean();
				node.setId(rs.getInt("id"));
				node.setMenuName(rs.getString("menu_name"));
				node.setMenuPage(rs.getString("menu_page"));
				node.setMenuCommand(rs.getString("menu_command"));
				node.setOrderId(rs.getInt("order_id"));
				node.setLevelId(rs.getInt("order_id"));
				node.setParentId(rs.getInt("menu_parent_id"));
				root.addChildToParent(node);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
					rs = null;
				} catch (final SQLException e) {
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
					stmt = null;
				} catch (final SQLException e) {
				}
			}
			return root;
		}
	}
	
	public static String getMenuPath(HttpSession session,int menuId){
		String return_val = "";
		MenuBean root = SessionFacade.getRootMenuBean(session);
		MenuBean currBean = root.getNodeById(menuId);
		while(currBean!=null&&currBean.getParentBean()!=null&&currBean.getLevelId()>0){
			return_val = currBean.getMenuName()+"&nbsp;>>&nbsp;"+return_val;
			currBean = currBean.getParentBean();
		}
		return_val = return_val.substring(0, return_val.length()-14);
		return return_val;
	}
}
